package server

import (
	"fmt"
	"gitee.com/snxamdf/wui/config"
	"gitee.com/snxamdf/wui/logs"
	"gitee.com/snxamdf/wui/util"
	"html/template"
	"io"
	"io/ioutil"
	"path/filepath"
	"strings"
)

var htmlTemplates = make(map[string]htmlTemplate)

type htmlTemplate struct {
	path     string
	name     string
	url      string
	template *template.Template
}

func CacheHtmlTemplates() {
	var (
		byt          []byte
		err          error
		templatePath = config.GetConfig("template")
		filePaths    = config.ReadFile(templatePath)
	)
	for _, path := range filePaths {
		_, name := filepath.Split(path)
		var url = strings.ReplaceAll(path, "\\", "/")
		url = url[len(fmt.Sprintf("%s/%s", config.AppResource, templatePath)):]
		logs.Info("CacheHtmlTemplates:", config.IsEnvDev(), name, url)
		if config.IsEnvDev() {
			byt, err = ioutil.ReadFile(path)
		} else {
			byt, err = config.GetEFS().ReadFile(path)
		}
		if err != nil {
			logs.Error("缓存Html模板错误：", err)
			continue
		}
		htmlTemplates[url] = htmlTemplate{
			path:     path,
			name:     name,
			url:      url,
			template: templateMust(url, string(byt)), //template.Must(template.New(url).Parse(string(byt))),
		}
	}
	logs.Debug("缓存Html模板数量：", len(htmlTemplates))
}

func templateMust(name, html string) *template.Template {
	return template.Must(template.New(name).Parse(html))
}

func writeHtmlTemplate(w io.Writer, template *template.Template, data interface{}) {
	if buf, err := util.HtmlTemplateBuffer(template, data); err == nil {
		io.Copy(w, buf)
	} else {
		logs.Error("响应输出Html模板错误：", err)
	}
}
